import { ref, onMounted, onUnmounted, computed } from 'vue'
import { filter } from '../utils/todoStorage'

const validHash = ['all', 'active', 'completed']

export default function (todos) {
	const visibility = ref('all') // 默认值为所有
	const onHashChange = function () {
		// hash变化时候我的处理函数
		const hash = location.hash.replace(/#\/?/, '')
		if (validHash.includes(hash)) {
			visibility.value = hash
		} else {
			location.hash = ''
			visibility.value = 'all'
		}
	}
	onMounted(() => {
		window.addEventListener('hashchange', onHashChange)
	})
	onUnmounted(() => {
		window.removeEventListener('hashchange', onHashChange)
	})
	const todosFiltered = computed(() => {
		return filter(todos.value, visibility.value)
	})
	const todosLefted = computed(() => {
		return todos.value.filter((todo) => !todo.completed)
	})
	const todosCompleted = computed(() => {
		return todos.value.filter((todo) => todo.completed)
	})
	return {
		visibility,
		todosFiltered,
		todosLefted,
		todosCompleted,
	}
}
